import store from '../../store/store';

//设置当前视图下的矩形区域
import BaiduImageryProvider from "../BaiduImageryProvider";

//加载JSON数据
export const loadGeoJson = function () {
  let YellowRiver_wgs84= viewer.dataSources.add(Cesium.GeoJsonDataSource.load('static/data/YellowRiver_wgs84.json', {
    stroke: Cesium.Color.HOTPINK,  //多边形轮廓的默认颜色
    fill: Cesium.Color.PINK,    //多边形内部的默认颜色。
    markerColor: Cesium.Color.RED, //获取或设置为每个点创建的地图针脚的默认颜色
    strokeWidth: 5,    //线段或者多边形默认宽度
    markerSymbol: 'name'   //是被标注字段
  }));
  viewer.zoomTo(YellowRiver_wgs84);
};

export const setRectangle = function(rectangle){
  viewer.camera.setView({
    destination: Cesium.Rectangle.fromDegrees(rectangle.west, rectangle.south, rectangle.east, rectangle.north)
  });
};

//获取当前矩形区域
export const getRectangle_copy = function(){
  let rectangle = viewer.camera.computeViewRectangle();
  for (let key in rectangle) {
    rectangle[key] = rectangle[key] / Math.PI * 180;
  }
  return rectangle;
  // let west =rectangle.west / Math.PI * 180;
  // let north = rectangle.north / Math.PI * 180;
  // let east = rectangle.east / Math.PI * 180;
  // let south = rectangle.south / Math.PI * 180;
};
export const getRectangle = function(){
  let params = {};
  let extend = viewer.camera.computeViewRectangle();
  if (typeof extend === "undefined") {
    //2D下会可能拾取不到坐标，extend返回undefined,所以做以下转换
    let canvas = viewer.scene.canvas;
    let upperLeft = new Cesium.Cartesian2(0, 0);//canvas左上角坐标转2d坐标
    let lowerRight = new Cesium.Cartesian2(
      canvas.clientWidth,
      canvas.clientHeight
    );//canvas右下角坐标转2d坐标

    let ellipsoid = viewer.scene.globe.ellipsoid;
    let upperLeft3 = viewer.camera.pickEllipsoid(
      upperLeft,
      ellipsoid
    );//2D转3D世界坐标

    let lowerRight3 = viewer.camera.pickEllipsoid(
      lowerRight,
      ellipsoid
    );//2D转3D世界坐标

    let upperLeftCartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(
      upperLeft3
    );//3D世界坐标转弧度
    let lowerRightCartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(
      lowerRight3
    );//3D世界坐标转弧度

    let minx = Cesium.Math.toDegrees(upperLeftCartographic.longitude);//弧度转经纬度
    let maxx = Cesium.Math.toDegrees(lowerRightCartographic.longitude);//弧度转经纬度

    let miny = Cesium.Math.toDegrees(lowerRightCartographic.latitude);//弧度转经纬度
    let maxy = Cesium.Math.toDegrees(upperLeftCartographic.latitude);//弧度转经纬度

    // console.log("经度：" + minx + "----" + maxx);
    // console.log("纬度：" + miny + "----" + maxy);

    params.west = minx;
    params.east = maxx;
    params.south = miny;
    params.north = maxy;
  } else {
    //3D获取方式
    params.east = Cesium.Math.toDegrees(extend.east);
    params.north = Cesium.Math.toDegrees(extend.north);

    params.west = Cesium.Math.toDegrees(extend.west);
    params.south = Cesium.Math.toDegrees(extend.south);
    // console.log("结果：" + JSON.stringify(params))
  }
  return params;//返回屏幕所在经纬度范围
};

//初始化地图
export const initMap = function(log){
  console.log("init:" + log);
  Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI3NjRjNGFjNy1jNDM3LTQzMTktODVlYS05YmFmOTAxYjk5MWUiLCJpZCI6Mzk5MSwic2NvcGVzIjpbImFzbCIsImFzciIsImFzdyIsImdjIl0sImlhdCI6MTUzOTU3OTE2NX0.-25udUzENRJ66mnICMK8Hfc6xgF_VP7P4sWkSHaUjOQ';
  window.viewer = new Cesium.Viewer('mapContainer', {
    sceneMode: Cesium.SceneMode.SCENE3D,
    infoBox: false, //信息框
    selectionIndicator: false, //绿色框
    imageryProvider: new Cesium.ArcGisMapServerImageryProvider({
      url: "http://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer",
    })
  });
  viewer.sceneModePicker.viewModel.duration = 0.0;//去掉二三维切换动画效果
  viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

  //可以监听切片的加载状态
  // helper = new Cesium.EventHelper();
  // helper.add(viewer.scene.globe.tileLoadProgressEvent, function (event) {
  //   // console.log('每次加载矢量切片都会进入这个回调');
  //   if (event === 0) {
  //     // console.log('这个是加载最后一个矢量切片的回调');
  //   }
  // });

  //初始视角（河南）
  viewer.camera.setView({destination: Cesium.Cartesian3.fromDegrees(113.6, 34.76, 500000)});
};

//重定位视角
export const relocation = function(){
  //视角飞行至目的地
  viewer.camera.setView({
    // destination: Cesium.Cartesian3.fromDegrees(113.6, 34.76, 500000),//郑州
    destination: Cesium.Cartesian3.fromDegrees(126.3524, 43.986, 2799838.567),
    // orientation: {
    //   heading:Cesium.Math.toRadians(360),
    //   pitch:Cesium.Math.toRadians(-70),
    //   roll: Cesium.Math.toRadians(0), //默认值8
    // },
  })
};

export const unloadMapFrame = function () {
  // helper.removeAll();
  viewer.destroy();
  store.state.currentFrameNameStore = '';
  window.viewer = null;
};

export const mapName = 'cesium';

//切换底图
export const changeBaseMap = function(type){
  viewer.scene.imageryLayers.removeAll();
  if(type === 'baidu'){
    let option = {
      "layer": "custom",
      "styles": "t%3Awater%7Ce%3Aall%7Cc%3A%230b2a3fff%2Ct%3Ahighway%7Ce%3Ag.f%7Cc%3A%2322425cff%2Ct%3Aarterial%7Ce%3Ag.s%7Cc%3A%231b374eff%2Ct%3Alocal%7Ce%3Ag.f%7Cc%3A%231b374eff%2Ct%3Aland%7Ce%3Aall%7Cc%3A%231e394dff%2Ct%3Arailway%7Ce%3Ag%7Cv%3Aoff%7Cc%3A%23000000ff%2Ct%3Asubway%7Ce%3Ag%7Cv%3Aoff%2Ct%3Abuilding%7Ce%3Ag.f%7Cc%3A%23000000ff%2Ct%3Aall%7Ce%3Al.t.f%7Cc%3A%23857f7f%2Ct%3Aall%7Ce%3Al.t.s%7Cc%3A%23020d17ff%2Ct%3Abuilding%7Ce%3Ag%7Cv%3Aon%7Cc%3A%231e394eff%2Ct%3Agreen%7Ce%3Ag%7Cv%3Aoff%7Cc%3A%23153145ff%2Ct%3Aboundary%7Ce%3Aall%7Cc%3A%23656a7aff%2Ct%3Amanmade%7Ce%3Ag%7Cc%3A%2324475aff%2Ct%3Apoi%7Ce%3Aall%7Cv%3Aoff%2Ct%3Aall%7Ce%3Al.i%7Cv%3Aoff%2Ct%3Aall%7Ce%3Al.t.f%7Cv%3Aon%7Cc%3A%236b9ac3ff%2Ct%3Ahighway%7Ce%3Ag.s%7Cv%3Aon%7Cc%3A%23132d45ff%2Ct%3Aarterial%7Ce%3Ag.f%7Cc%3A%23162e45ff%2Ct%3Alocal%7Ce%3Ag.s%7Cc%3A%231a324aff"
    };
    viewer.scene.imageryLayers.addImageryProvider(
      new BaiduImageryProvider(option)
    );
  }else if(type === 'arcgis'){
    viewer.scene.imageryLayers.addImageryProvider(
      new Cesium.ArcGisMapServerImageryProvider({
        // url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
        url: 'http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineStreetPurplishBlue/MapServer',
        enablePickFeatures: false
      })
    );
  }else if(type === 'gaode'){
    viewer.imageryLayers.addImageryProvider(
      new Cesium.UrlTemplateImageryProvider({
        url: "http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
      })
    );
  }else if(type === 'tianditu'){
    // viewer.imageryLayers.addImageryProvider(
    //   new Cesium.WebMapTileServiceImageryProvider({
    //     // // url: "http://{s}.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=53fa4c6322d455b68afac58ecc41d941",
    //     // url: "http://t0.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=53fa4c6322d455b68afac58ecc41d941",
    //     // layer: "tdtBasicLayer",
    //     // style: "default",
    //     // maximumLevel:20,
    //     // format: "image/jpeg",
    //     // tileMatrixSetID: "GoogleMapsCompatible",
    //     // show: true,
    //     // subdomains:["t0","t1","t2","t3","t4","t5","t6","t7"]
    //
    //     url:'http://{s}.tianditu.gov.cn/cta_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cta&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=53fa4c6322d455b68afac58ecc41d941',
    //     layer:'img',
    //     style:'default',
    //     format:'tiles',
    //     tileMatrixSetID:'w',
    //     subdomains:['t0','t1','t2','t3','t4','t5','t6','t7'],
    //     // credit:new that.Cesium.Credit('天地图影像'),
    //     maximumLevel:18
    //
    //
    //   })
    // );
    
    //测试https
    viewer.imageryLayers.addImageryProvider(loadTianDiTU('地形图'));
    
    
  }else if(type === 'geoserver'){ //tomcat有跨域问题
    // let matrixIds = ['EPSG:4326:0', 'EPSG:4326:1', 'EPSG:4326:2', 'EPSG:4326:3', 'EPSG:4326:4', 'EPSG:4326:5', 'EPSG:4326:6', 'EPSG:4326:7', 'EPSG:4326:8', 'EPSG:4326:9', 'EPSG:4326:10',
    //   'EPSG:4326:11', 'EPSG:4326:12', 'EPSG:4326:13', 'EPSG:4326:14', 'EPSG:4326:15', 'EPSG:4326:16', 'EPSG:4326:17', 'EPSG:4326:18', 'EPSG:4326:19', 'EPSG:4326:20', 'EPSG:4326:21'];

    let matrixIds = ['EPSG:3857_ChangChunShi:0', 'EPSG:3857_ChangChunShi:1', 'EPSG:3857_ChangChunShi:2', 'EPSG:3857_ChangChunShi:3', 'EPSG:3857_ChangChunShi:4', 'EPSG:3857_ChangChunShi:5', 'EPSG:3857_ChangChunShi:6', 'EPSG:3857_ChangChunShi:7', 'EPSG:3857_ChangChunShi:8', 'EPSG:3857_ChangChunShi:9', 'EPSG:3857_ChangChunShi:10',
      'EPSG:3857_ChangChunShi:11', 'EPSG:3857_ChangChunShi:12', 'EPSG:3857_ChangChunShi:13', 'EPSG:3857_ChangChunShi:14', 'EPSG:3857_ChangChunShi:15', 'EPSG:3857_ChangChunShi:16', 'EPSG:3857_ChangChunShi:17', 'EPSG:3857_ChangChunShi:18', 'EPSG:3857_ChangChunShi:19', 'EPSG:3857_ChangChunShi:20', 'EPSG:3857_ChangChunShi:21'];

    viewer.imageryLayers.addImageryProvider(
      new Cesium.WebMapTileServiceImageryProvider({
        url:'http://111.26.1.82:8888/geowebcache/service/wmts',  //√
        layer:'ChangChunShi',  //√
        format: "image/png",  //√
        style:'',
        tileMatrixLabels: matrixIds,
        // maximumLevel: 21,  //暂时注释掉
        tileMatrixSetID:"EPSG:3857_ChangChunShi",  //√
      })
    );

    // let wmtsImageryProvider = new Cesium.WebMapTileServiceImageryProvider({
    //   url : 'http://111.26.1.82:8888/geowebcache/service/wmts/ChangChunShi/{style}/{TileMatrixSet}/{TileMatrixSet}:{TileMatrix}/{TileRow}/{TileCol}?format=image/png',
    //   layer : 'ChangChunShi',
    //   style : '',
    //   format : 'image/png',
    //   tileMatrixSetID:'EPSG:3857'      //一般使用EPSG:3857坐标系
    // });
    // viewer.imageryLayers.addImageryProvider(wmtsImageryProvider);

    // let wgs84=new Cesium.GeographicTilingScheme();
    // let url2='http://111.26.1.82:8888/geowebcache/service/wmts?layer=ChangChunShi&style=&tilematrixset=EPSG:4326&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image/png&TileMatrix=EPSG:4326:{TileMatrix}&TileCol={TileCol}&TileRow={TileRow}';
    // let provider5 = new Cesium.WebMapTileServiceImageryProvider({
    //   url:url2,
    //   layer:'ChangChunShi',
    //   style:'raster',
    //   tileMatrixSetID:"EPSG:4326",
    //   tilingScheme:wgs84
    // });
    // viewer.imageryLayers.addImageryProvider(provider5);



  }else if(type === '亮色'){
    viewer.scene.imageryLayers.addImageryProvider(
      new Cesium.ArcGisMapServerImageryProvider({
        url: "http://arcgis-server.fpi-inc.site/arcgis/rest/services/jilin/light_c/MapServer",
        enablePickFeatures: false,
        maximumLevel:7,//11
        minimumLevel:1
      })
    );
    viewer.scene.screenSpaceCameraController.minimumZoomDistance = 2500;//相机的高度的最小值
    // viewer.scene.screenSpaceCameraController.maximumZoomDistance = 2000000;  //相机高度的最大值
    viewer.scene.screenSpaceCameraController._minimumZoomRate = 30000; // 设置相机缩小时的速率
    // viewer.scene.screenSpaceCameraController._maximumZoomRate=1626856    //设置相机放大时的速率
  }else if(type === '暗色'){
    viewer.scene.imageryLayers.addImageryProvider(
      new Cesium.ArcGisMapServerImageryProvider({
        url: "http://arcgis-server.fpi-inc.site/arcgis/rest/services/jilin/dark_cnn/MapServer",
        enablePickFeatures: false,
        maximumLevel:7,//11
        minimumLevel:1
      })
    );
  }else if(type === '新配图'){
    viewer.scene.imageryLayers.addImageryProvider(
      new Cesium.ArcGisMapServerImageryProvider({
        url: "http://arcgis-server.fpi-inc.site/arcgis/rest/services/jilin/light_0923/MapServer",
      })
    );
    viewer.scene.screenSpaceCameraController.minimumZoomDistance = 2500;//相机的高度的最小值
    // viewer.scene.screenSpaceCameraController.maximumZoomDistance = 2000000;  //相机高度的最大值
    viewer.scene.screenSpaceCameraController._minimumZoomRate = 30000; // 设置相机缩小时的速率
    // viewer.scene.screenSpaceCameraController._maximumZoomRate=1626856    //设置相机放大时的速率
  }
  else if(type === '叠图层'){
    viewer.imageryLayers.addImageryProvider(new Cesium.GridImageryProvider());//添加注记图层
  }
};

function loadTianDiTU(type){
  //https
  let ter_w = "https://t0.tianditu.gov.cn/ter_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=ter&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=73ce9d0155c8c10c44b0c60f94d65c13"//地形图
  let cta_w = "https://t0.tianditu.gov.cn/cta_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cta&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=73ce9d0155c8c10c44b0c60f94d65c13"//地形图 注记
  //http
  let img_w = "http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=73ce9d0155c8c10c44b0c60f94d65c13"//影像图
  let cia_w = "http://t0.tianditu.com/cta_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=73ce9d0155c8c10c44b0c60f94d65c13"//影像图 注记
  
  let option =  {
    "url": "",
    "layer": "tdtImgBasicLayer",
    "style": "default",
    "format": "image/png",
    "tileMatrixSetID": "GoogleMapsCompatible",
    "show": false
  }
  switch (type) {
    case '地形图':
      option.url = ter_w
      return new Cesium.WebMapTileServiceImageryProvider(option)
      break;
      
  
  }
  
  // option.url = cta_w
  // this.TianDiTerAnnoProvider = new Cesium.WebMapTileServiceImageryProvider(option)
  // option.url = img_w
  // this.TianDiImgProvider = new Cesium.WebMapTileServiceImageryProvider(option)
  
  
}
